package com.simafei.flow.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simafei.flow.core.common.Enabled;
import com.simafei.flow.core.json.JsonUtils;
import com.simafei.flow.web.common.PageUtils;
import com.simafei.flow.web.dao.ApiMapper;
import com.simafei.flow.web.domain.req.ApiReq;
import com.simafei.flow.web.domain.req.PageParam;
import com.simafei.flow.web.domain.req.VariableReq;
import com.simafei.flow.web.domain.resp.ApiResp;
import com.simafei.flow.web.domain.resp.PageResult;
import com.simafei.flow.web.entity.ApiPO;
import com.simafei.flow.web.service.IApiService;
import com.simafei.flow.web.transfer.ApiTransfer;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 算法模型表 服务实现类
 * </p>
 *
 * @author fengpengju
 * @since 2024-06-18
 */
@Service
public class ApiServiceImpl extends ServiceImpl<ApiMapper, ApiPO> implements IApiService {

    @Override
    public ApiResp get(Long id) {
        ApiPO api = getById(id);
        return ApiTransfer.INSTANCE.toResp(api);
    }

    @Override
    public Long add(ApiReq req) {
        ApiPO api = ApiTransfer.INSTANCE.toPo(req);
        save(api);
        return api.getId();
    }

    @Override
    public boolean update(Long id, ApiReq req) {
        ApiPO api = ApiTransfer.INSTANCE.toPo(req);
        api.setId(id);
        return updateById(api);
    }

    @Override
    public boolean setRespVariables(Long apiId, List<VariableReq> variables) {
        return update(new LambdaUpdateWrapper<ApiPO>()
                .set(ApiPO::getApiStatus, Enabled.ENABLED.getValue())
                .set(ApiPO::getRespVariables, JsonUtils.toJsonString(variables))
                .eq(ApiPO::getId , apiId));
    }

    @Override
    public List<ApiResp> queryByName(String apiName) {
        List<ApiPO> list = list(new LambdaQueryWrapper<>(ApiPO.class).like(ApiPO::getApiName, apiName));
        return ApiTransfer.INSTANCE.toResp(list);
    }

    @Override
    public PageResult<ApiResp> queryPage(PageParam param, boolean enabled) {
        Page<ApiPO> page = page(new Page<>(param.getPageNo(), param.getPageSize()),
                new LambdaQueryWrapper<ApiPO>().eq(ApiPO::getApiStatus, enabled ? 1 : 0));
        return PageUtils.buildPageResult(page, ApiTransfer.INSTANCE::toResp);
    }

    @Override
    public PageResult<ApiResp> queryPage(PageParam param) {
        Page<ApiPO> page = page(new Page<>(param.getPageNo(), param.getPageSize()));
        return PageUtils.buildPageResult(page, ApiTransfer.INSTANCE::toResp);
    }
}
